/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.store.entity.TStoreSellerEntity;
import io.renren.modules.store.entity.TStoreStaffEntity;
import io.renren.modules.store.service.TStoreSellerService;
import io.renren.modules.store.service.TStoreStaffService;
import io.renren.modules.sys.entity.OnDutyUserVo;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TStoreStaffService storeStaffService;
    @Autowired
    private TStoreSellerService storeSellerService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 注册
     */
    @PostMapping("/sys/register")
    public R register(@RequestBody RegisterForm registerForm) {
        SysUserEntity user = sysUserService.register(registerForm.getMobile(), registerForm.getPassword());
        return R.ok();
    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) throws IOException {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        //changeWork();
        return r;
    }

    //保存当班信息
    @RequestMapping("/keepChangeWorkInfo")
    public void keepChangeWorkInfo() {
        String onDutyInfo = "on_duty_user_" + getUserId() + "_" + getSeller();
        Boolean hasKey = redisTemplate.hasKey(onDutyInfo);
        if (!hasKey) {
            OnDutyUserVo onDutyUserVo = new OnDutyUserVo();
            List<TStoreSellerEntity> seller = storeSellerService.list(new QueryWrapper<TStoreSellerEntity>()
                    .eq("user_id", getUserId())
            );
            if (seller.size() == 0) {
                TStoreStaffEntity user = storeStaffService.getOne(new QueryWrapper<TStoreStaffEntity>()
                        .eq("user_id", getUserId())
                );
                onDutyUserVo.setOnDutyTime(new Date());
                onDutyUserVo.setSellerId(user.getSellerId());
                onDutyUserVo.setUserName(user.getStaffName());
                onDutyUserVo.setUserTel(user.getStaffTel());
                onDutyUserVo.setUserId(user.getUserId());
                Map<String, Object> map = BeanUtil.beanToMap(onDutyUserVo);
                redisTemplate.opsForHash().putAll(onDutyInfo,map);
            }
            else {
                for (TStoreSellerEntity tStoreSellerEntity : seller) {
                    if (tStoreSellerEntity.getSellerId().equals(getSeller())) {
                        onDutyUserVo.setOnDutyTime(new Date());
                        onDutyUserVo.setSellerId(tStoreSellerEntity.getSellerId());
                        onDutyUserVo.setUserId(tStoreSellerEntity.getUserId());
                        onDutyUserVo.setUserName(tStoreSellerEntity.getLinkName());
                        onDutyUserVo.setUserTel(tStoreSellerEntity.getLinkTel());
                    }
                }
                Map<String, Object> map = BeanUtil.beanToMap(onDutyUserVo);
                redisTemplate.opsForHash().putAll(onDutyInfo,map);
            }
        }
    }


    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

}
